package com.crs.controller.user;

import com.crs.dto.ResourcePubDTO;
import com.crs.dto.ResourcesPageQueryDTO;
import com.crs.entity.Resource;
import com.crs.result.PageResult;
import com.crs.result.Result;
import com.crs.service.ResourceService;
import com.crs.service.UserService;
import com.crs.vo.ResourceListVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Size;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user/resource")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @PostMapping("/pub")
    public Result ResourcePub(HttpServletRequest request) {
        try {
            // 打印请求信息
            log.info("收到请求，Content-Type: {}", request.getContentType());
            log.info("所有参数名: {}", Collections.list(request.getParameterNames()));

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

            // 获取并验证普通字段
            String name = multipartRequest.getParameter("name");
            String categoryIdStr = multipartRequest.getParameter("categoryId");
            String location = multipartRequest.getParameter("location");
            String description = multipartRequest.getParameter("description");

            // 参数验证
            if (StringUtils.isEmpty(name)) {
                return Result.error("资源名称不能为空");
            }

            Integer categoryId;
            try {
                categoryId = Integer.valueOf(categoryIdStr);
            } catch (NumberFormatException e) {
                return Result.error("分类ID格式不正确");
            }

            if (StringUtils.isEmpty(location)) {
                return Result.error("位置不能为空");
            }

            if (StringUtils.isEmpty(description)) {
                return Result.error("描述不能为空");
            }

            // 获取并验证文件
            List<MultipartFile> files = multipartRequest.getFiles("files");
            if (files == null || files.isEmpty()) {
                return Result.error("请上传至少一个文件");
            }

            // 验证文件
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    return Result.error("文件不能为空");
                }
                if (!file.getContentType().startsWith("image/")) {
                    return Result.error("只支持图片文件");
                }
                if (file.getSize() > 10 * 1024 * 1024) {
                    return Result.error("文件大小不能超过10MB");
                }
            }

            // 构建DTO
            ResourcePubDTO dto = ResourcePubDTO.builder()
                    .name(name)
                    .categoryId(categoryId)
                    .location(location)
                    .description(description)
                    .build();

            // 调试日志
            log.info("构建的DTO: {}", dto);
            log.info("文件数量: {}", files.size());

            resourceService.pub(dto, files);
            return Result.success();

        } catch (Exception e) {
            log.error("资源发布失败", e);
            return Result.error("资源发布失败：" + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result<PageResult> ResourceList(ResourcesPageQueryDTO resourcesPageQueryDTO){
        log.info("查看资源列表，参数：{}", resourcesPageQueryDTO);
        PageResult pageResult = resourceService.list(resourcesPageQueryDTO);
        return Result.success(pageResult);
    }

    @GetMapping("/detail/{id}")
    public Result<ResourceListVo> ResourceDetail(@PathVariable Integer id){
        log.info("查看资源详情");
        ResourceListVo resourceListVo = resourceService.detail(id);
        return Result.success(resourceListVo);
    }
}
